package com.up.interview.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: liuchengjun
 * @title: ThreadPoolManger
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description:
 * @date: 2025/10/21/周二 14:28 (星期二)
 * @since V2.0
 */
public class ThreadPoolManger {

    /**
     * 创建线程池
     * 核心线程：
     * 最大线程：
     * 最大线程超时时间：
     * 最大线程超时单位：
     * 阻塞队列：指定大小
     * 线程工厂
     * 核心线程回收配置：使用场景少开启：workerThreadPool.allowCoreThreadTimeOut(true);
     * 拒绝策略
     * @return
     */
    public ThreadPoolExecutor getThreadPoolExecutor() {
        int coreSize = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor workerThreadPool = new ThreadPoolExecutor(coreSize, coreSize,
                60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000), new ThreadFactory() {
            private final AtomicInteger threadIndex = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, String.format("workFlowDefinition-thread-%d", this.threadIndex.incrementAndGet()));
            }
        },new CustomRejectedExecutionHandler());
        workerThreadPool.allowCoreThreadTimeOut(true);
        return workerThreadPool;
    }

    class CustomRejectedExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            throw new RejectedExecutionException();
        }
    }
}
